package com.example.resource;

import com.example.anonation.AppLog;
import com.example.biz.IUserBiz;
import com.example.entity.User;
import org.springframework.beans.factory.annotation.Autowired;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.io.*;
import java.util.List;

/**
 * Created by 01182800 on 2017/2/24.
 */
@Path("users")
public class UserResource {

    @Autowired
    private IUserBiz userBiz;

    @AppLog
    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public List<User> findAll() {
        return this.userBiz.findAll();
    }

    @GET
    @Path("{id:[0-9]*}")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public User queryByPath(@PathParam("id") Integer id) {
        return this.userBiz.getById(id);
    }

    @GET
    @Path("user")
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public User queryByQuery(@QueryParam("id") Integer id) {
        return this.userBiz.getById(id);
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public User createUser(User user) {
        this.userBiz.save(user);
        return user;
    }

    @PUT
    @Path("{id:[0-9]*}")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    public String updateUser(@PathParam("id") Integer id, User user) {
        user.setId(id);
        this.userBiz.update(user);
        return "success";
    }

    @DELETE
    @Path("{id:[0-9]*}")
    @Produces(MediaType.TEXT_PLAIN)
    public String deleteUser(@PathParam("id") Integer id) {
        this.userBiz.delete(id);
        return "success";
    }

    @POST
    @Path("upload")
    public File uploadAndDownload(final File file) throws FileNotFoundException, IOException {
        BufferedReader br = new BufferedReader(new FileReader(file));
        String line = null;
        System.out.println("--------------------");
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        System.out.println("--------------------");
        return file;
    }

}
